<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/20
 * Time: 18:13
 */
namespace app\admin\model;

class Api extends BaseModel
{
    protected $autoWriteTimestamp = true;

    // status属性读取器
    protected function getStatusAttr($value)
    {
        $status = [ 0 => '禁用', 1 => '启用'];
        return $status[$value];
    }

    //请求方式读取器
    protected function getRequestAttr($value)
    {
        $request = [ 0 => '全部', 1=> 'GET', 2 => 'POST'];
        return $request[$value];
    }

    public function params()
    {
        return $this->hasMany('Param','id','api_id');
    }

    public function apiGroup()
    {
        return $this->hasOne('ApiGroup');
    }


    public function getApiList($page = '',$user_id)
    {
        $this->count = $this->count();

        $whe = '';
        if($user_id){
            $whe = 'WHERE a.user_id="'.$user_id.'"';
        }
        return $this->query('SELECT a.id,a.url,a.name,a.status,IF(a.status,"启用","禁用") AS statusMsg,
(SELECT COUNT(*) FROM param WHERE(api_id=a.id AND TYPE=0)) AS paramNum,
(SELECT COUNT(*) FROM param WHERE(api_id=a.id AND TYPE=1)) AS resultNum,
g.name AS groupName,u.name AS user_name,
CASE a.request WHEN 1 THEN "GET" WHEN 2 THEN "POST" END AS request,a.sort,FROM_UNIXTIME(a.create_time, \'%Y-%m-%d %H:%i:%S\') AS create_time
FROM api a 
INNER JOIN user u ON u.id=a.user_id 
INNER JOIN api_group g ON g.id=a.group_id '.$whe.' order by id desc 
limit '.$this->getLimitStart($page).','.$this->limit);
    }

}